package com.crazy.util.lock.wait;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author panyonghui
 * @describe Condition中等待和唤醒线程示例
 * @date 2022/1/13 10:34
 */
public class Demo2 {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    static class Th extends Thread{
        @Override
        public void run() {
            System.out.println(this.getName() + "准备获取锁");
            lock.lock();
            try {
                System.out.println(this.getName() + "获取到锁，让出资源进行等待");
                condition.await();
                System.out.println(this.getName() + "准备释放锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(this.getName() + "执行结束，释放锁");
        }
    }

    static class Th2 extends Thread{
        @Override
        public void run() {
            System.out.println(this.getName() + "准备获取锁");
            lock.lock();
            try {
                System.out.println(this.getName() + "获取到锁，唤醒等待线程");
                condition.signal();
                TimeUnit.SECONDS.sleep(3);
                System.out.println(this.getName() + "准备释放锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(this.getName() + "执行结束，释放锁");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Th th = new Th();
        th.setName("T1");
        Th2 th2 = new Th2();
        th2.setName("T2");
        th.start();
        TimeUnit.SECONDS.sleep(2);
        th2.start();
    }
}
